# -*- coding:utf-8 -*-
# from baidu_ocr.baidu_aip_test import execute_ocr
import os
import re
import sys
import threading
from time import ctime, sleep

from aip import AipOcr

__author__ = 'gin.chen'

from PIL import ImageGrab
import time


# 配置类
class Properties(object):
    def __init__(self, file_name):
        self.fileName = file_name
        self.properties = {}
        with open(self.fileName, 'r') as pro_file:
            for line in pro_file.readlines():
                line = line.strip().replace('\n', '')
                if line.find("#") != -1:
                    line = line[0:line.find('#')]
                if line.find('=') > 0:
                    strs = line.split('=')
                    strs[1] = line[len(strs[0]) + 1:]
                    self.properties[strs[0].strip()] = strs[1].strip()

    def get_properties(self):
        return self.properties


# 读取基本配置
__base_config_file = os.path.join(os.path.dirname(__file__), 'base.config')
config = Properties(__base_config_file).get_properties()
# 初始化接口
client = AipOcr(config['APP_ID'], config['API_KEY'], config['SECRET_KEY'])


def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 执行ocr
def execute_ocr(image):
    image = get_file_content(image)
    # image = make_shot()
    # return client.basicAccurate(image)
    # return client.enhancedGeneral(image)
    return client.basicGeneral(image)


# 使用截图
def PIL_shot():
    box = (int(config['x']), int(config['y']), int(config['m']), int(config['n']))
    im = ImageGrab.grab(box)
    # return im.tobytes()
    im.save('path-to-save', 'png')


def exec_after_deal(path, last):
    res = execute_ocr(bytes(path, encoding="utf8"))
    now = res.get('words_result')
    context = None
    if last != now and now is not None:
        if len(now) != 0:
            context = now[0].get('words')
            if last is not None:
                if len(last) != 0:
                    last_context = last[0].get('words')
                    last_patter = last_context[:3]
                    if re.match(last_patter, context) is None:
                        print(context)
                        with open('save.txt', 'a') as f:
                            f.write(context)
            else:
                print(context)
                with open('save.txt', 'a') as f:
                    f.write(context)

    # last = now
    # return now
    exec_after_deal(path, now)


def schedule_capture():
    while 1:
        time.sleep(1)
        PIL_shot()


if __name__ == '__main__':
    i = 0
    last = None
    path = os.path.abspath(os.path.dirname(sys.argv[0])) + '\\path-to-save'
    threads = [threading.Thread(target=schedule_capture), threading.Thread(target=exec_after_deal, args=(path, last))]
    for i in range(0, len(threads)):
        threads[i].start()
    for i in range(0, len(threads)):
        threads[i].join()

    # end = time.time()
    # print(end - beg)
